﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.Web.Mvc;
using System.Runtime.Serialization;
using System.Collections.Generic;

namespace MvcServiceLibrary
{
    public class ServiceViewFactory : WebFormViewFactory
    {
        private bool isAjaxRequest = false;
        protected internal virtual bool IsAjaxRequest
        {
            get
            {
                return isAjaxRequest;
            }
        }

        private bool isJsonRequest = false;
        protected internal virtual bool IsJsonRequest
        {
            get
            {
                return isJsonRequest;
            }
        }

        protected override IView CreateView(ControllerContext controllerContext, string viewName, string masterName, object viewData)
        {
            IHttpRequest request = controllerContext.HttpContext.Request;

            ResponseType responseType = request.GetResponseType();

            if (responseType == ResponseType.None)
            {
                // A format was specified that we don't understand - return an error
                throw new HttpException(400, "Unrecognized format specified" );
            }

            // We've checked for "None" (meaning an unknown format)
            // Now, if a serialized format was requested, do some additional validation
            if (responseType != ResponseType.Html)
            {
                if (viewData != null)
                {
                    switch (responseType)
                    {
                        // Serialize as XML
                        case ResponseType.Xml:
                            return new XmlSerializedView();

                        // Serialize as JSON
                        case ResponseType.Json:
                            return new JsonSerializedView();
                    }
                }
                else
                {
                    // We are unable to serialize the data:
                    // this is a server-side error
                    throw new HttpException(500, "Server Error: Unable to create properly formatted content.");
                }
            }
            else if 
                (String.IsNullOrEmpty(masterName) &&
                (!String.IsNullOrEmpty(request.Headers["Ajax"]) ||
                "XMLHttpRequest".Equals(request.Headers["X-Requested-With"],
                StringComparison.InvariantCultureIgnoreCase)))
            {
                masterName = "ajax";
            }

            return base.CreateView(controllerContext, viewName, masterName, viewData);
        }
    }
}
